//
//  EMSSkillPlannerTreeNode.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 4/29/09.
//  Copyright 2009  __Vadim__. All rights reserved.
//

#import "EMSSkillPlannerTreeNode.h"
#import "EVECDCharacter.h"
#import "EVECDLearnedSkill.h"
#import "EVECDSkill.h"

@implementation EMSSkillPlannerTreeNode

@synthesize level;
@synthesize learnedSkill=_representedObject;
@dynamic trainingStatus;

-(void)dealloc
{
	if(learnedSkill) [learnedSkill release];
	[super dealloc];
}

+(id)treeNodeWithLearnedSkill:(EVECDLearnedSkill*)skill level:(int)aLevel
{
	EMSSkillPlannerTreeNode* newNode = [self treeNodeWithRepresentedObject:skill];
	newNode.level = aLevel;
	return newNode;
}

-(TrainingStatus)trainingStatus
{
	TrainingStatus status = 0;
	if(!self.parentNode)
	{
		status |= trainingStatusRequestedSkill;
	}
	if(self.learnedSkill.currentlyInTraining.boolValue)
	{
		status |= trainingStatusInTraining;
	}
	if(self.learnedSkill.level.intValue >= self.level)
	{
		status |= trainingStatusLearnedEnough;
	} else {
		BOOL learnable = YES;
		for(EMSSkillPlannerTreeNode* childNode in self.childNodes)
		{
			if(!(childNode.trainingStatus & trainingStatusLearnedEnough))
			{
				learnable = NO;
				continue;
			}
		}
		status = learnable ? (status | trainingStatusLearnable) : status;
	}
	return status;
}

-(NSTimeInterval)thisTime
{
	NSTimeInterval total = 0;
	TrainingStatus status = self.trainingStatus;
	if(!(status & trainingStatusLearnedEnough))
	{
		total = [EMSSkillTrainingInfo trainingTimeToLevel:self.level forSkill:self.learnedSkill];
	}
	return total;
}

-(NSTimeInterval)prequisiteTime
{
	NSTimeInterval total = 0;
	TrainingStatus status = self.trainingStatus;
	if(!((status & trainingStatusLearnedEnough) || (status & trainingStatusLearnable)))
	{
		for(EMSSkillPlannerTreeNode* childNode in self.childNodes)
		{
			total += (childNode.thisTime + childNode.prequisiteTime);
		}
	}
	return total;
}

-(NSString*)description
{
	NSMutableString* description = [NSMutableString stringWithFormat:@"Self skill: %@, level: %i(", self.learnedSkill.skill.name, self.level];
	for(EMSSkillPlannerTreeNode* childNode in self.childNodes)
	{
		[description appendFormat:@"\nChild Node -> %@", childNode.description];
	}
	[description appendString:@")"];
	return description;
}

@end
